using UnityEngine;
using System.Collections;

public class cCar : MonoBehaviour {
	
	/*
	 * Parts
	 */
	public GameObject []enginePrefabList;
	
	public GameObject Engine;
	public GameObject Handle;

	/*
	 * Status
	 */
	public float Speed;
	public float Weigth;
	
	public Vector3 _Inertia;
	private Vector3 _Crash2Normal;
	
	public bool bCrash = false;
	
	
	public Animation _CarAnimation;
	public AnimationClip _currentAnimation = null;
	public AnimationClip CarIdle;
	
	// debug 
	Vector3 _cPos = new Vector3(0,0,0);
	Vector3 _cRay = new Vector3(0,0,0);
	
	void Awake()
	{
		//_CarAnimation = GetComponent<Animation>(); 
	}
	
	// Use this for initialization
	void Start () {
		
		_currentAnimation = CarIdle;
		/*
		 * 엔진 교체 셈플
		 */
		
		/*
		GameObject engineObject = (GameObject)Instantiate(enginePrefabList[1]);
		engineObject.transform.parent = transform;
		
		if ( engineObject )
		{
			Destroy(Engine);
			
			Engine = engineObject.gameObject;
		}
		else{
			
			engineObject = (GameObject)Instantiate(enginePrefabList[0]);
			if ( engineObject )
			{
				Destroy(Engine);
				Engine = engineObject.gameObject;
			}
		}
		*/
		//if ( !Engine )
		{
			
			//GameObject engineObject = (GameObject)Instantiate(enginePrefabList[0]);
			GameObject engineObject = (GameObject)Instantiate(Engine);
			
			engineObject.transform.parent = transform;
			
			if ( engineObject )
			{
				//Destroy(Engine);
				
				Engine = engineObject.gameObject;
				
				engineObject.transform.parent = transform;
				
			}
			
		}
		
		//if ( !Handle )
		{
			
			GameObject handleObject = (GameObject)Instantiate(Handle);
			
			handleObject.transform.parent = transform;
			
			if ( handleObject )
			{
				//Destroy(Handle);
				
				Handle = handleObject.gameObject;
				
				handleObject.transform.parent = transform;
				
			}

		}
		_Inertia = transform.forward;

		
		GameObject foundObj = GameObject.Find("load_path" );
		
		if ( foundObj )
		{
			
			cLoadPathManager lpMan = (cLoadPathManager)foundObj.GetComponent("cLoadPathManager");
			
			if ( lpMan )
			{
				
				cPathPoint pp = lpMan.GetNearPath( transform.position, -1 );
				
				Debug.Log ( pp.ToString() );
				
			}

		}

	}
	
	// Update is called once per frame
	void Update () {
		
		_Inertia.Normalize();
		_Inertia += transform.forward;
		_Inertia.Normalize();
		/*
		 * 차가 뒤집어 지는것을 방지한다.
		 */
		
		Quaternion rot = transform.rotation;
		
		Vector3 tempPos = transform.position;
		
		if ( tempPos.y < 1f ) tempPos.y = 1f;
		
		else if ( tempPos.y > 1f ) tempPos.y = 1f;
		
		transform.position = tempPos;
		/*
		if ( rot.x > 0.1f )
			
			rot.x = 0.1f;
		
		else if ( rot.x < -0.1f )
			
			rot.x = -0.1f;
		
		if ( rot.z > 0.1f )
			
			rot.z = 0.1f;
		
		else if ( rot.z < -0.1f )
			
			rot.z = -0.1f;
		
		transform.rotation = rot;
		*/
		cEngine CurrentEngine = (cEngine)Engine.GetComponent("cEngine");//("Engine");
		
		
		bool bAccOrBreak = false;
		
		if ( CurrentEngine != null )
		{
			
			cCarHandle CurrentHandle = (cCarHandle)Handle.GetComponent("cCarHandle");
			
			float rotateSpeed = CurrentHandle.RotateSpeed;

			if ( Input.GetKey( KeyCode.A ) )
			{
				
				//if ( Speed != 0f )
					transform.Rotate(Vector3.up * -rotateSpeed* Time.deltaTime);
				
			}
			if ( Input.GetKey( KeyCode.D ) )
			{
				
				//if ( Speed != 0f )
					transform.Rotate(Vector3.up * rotateSpeed* Time.deltaTime);
				
			}
			
			if ( !bCrash )
			{
				
				if ( Input.GetKey( KeyCode.W ) )
				{
					
					float aa = CurrentEngine.MaxTorque;
					
					bAccOrBreak = true;
					
					Speed += aa;
					
					if ( Speed >= CurrentEngine.MaxRPM )
						
						Speed = CurrentEngine.MaxRPM;
					
				}
				else if ( Input.GetKey( KeyCode.S ) )
				{
					
					float aa = CurrentEngine.MaxTorque;
					
					bAccOrBreak = true;
					
					Speed += (-aa);
					
					if ( Speed <= -CurrentEngine.MaxRPM * 0.8f )
						
						Speed = -CurrentEngine.MaxRPM * 0.8f;
	
				}
			
			}
			
		}
		
		if ( !bAccOrBreak )
			Speed = Speed * 0.97f;
		
		if ( !bCrash )
		{
			Vector3 fwd = transform.forward + _Inertia;
			fwd.Normalize();
			transform.position += (fwd * Speed * Time.deltaTime);
			
			
			//if ( Vector3.Angle(_Inertia,transform.forward) > 4f )
				//Speed *= 0.9f;//transform.Rotate(Vector3.up * -rotateSpeed* Time.deltaTime);
				
			//Debug.Log ( Vector3.Angle(_Inertia,transform.forward).ToString() );
			//fwd.Normalize();
			//transform.Translate(Vector3.forward * Speed * Time.deltaTime);
			//transform.Translate(fwd * Speed * Time.deltaTime);
		}
		
		if ( bCrash )
		{
			Vector3 newPos = transform.position + _Crash2Normal* Time.deltaTime;
			//transform.Translate(_Crash2Normal *10f* Time.deltaTime );
			newPos.y = 1;
			transform.position = newPos;
/*			
			_fCrashTime -= Time.deltaTime;
			
			if ( _fCrashTime < 0f )
			{
				
				bCrash = false;
				_fCrashTime = 0f;
				
			}
*/
		}
		
		//if ( _cPos && _cRay )
		Debug.DrawLine( _cPos, _cRay, Color.red );
		
		if ( !_CarAnimation.isPlaying )
		{
			_currentAnimation = CarIdle;
			_CarAnimation[_currentAnimation.name].time = 0.0f;
			_CarAnimation.CrossFade(_currentAnimation.name);
			_CarAnimation.Play (_currentAnimation.name);
		}
		
	}
	
	void OnTriggerExit(Collider obj)
	{
		if ( obj.gameObject.name == "Wall" )
		{
			
			bCrash = false;
			_Crash2Normal.x = 0;
			_Crash2Normal.y = 0;
			_Crash2Normal.z = 0;
			
/*			Vector3 ang = transform.position - obj.transform.position;
			ang.Normalize();
			
			Quaternion newro =  Quaternion.LookRotation(ang);
			
			newro *= transform.localRotation;
				
			transform.rotation = newro;*/
			
		}
	}
	
	void OnCollisionEnter(Collision obj)
	{
		Debug.Log("enter");
	}
	
	void OnCollisionExit(Collision obj)
	{
		Debug.Log("exit");
	}

	void OnTriggerEnter(Collider obj) {
	
		if ( obj.gameObject.name == "Wall" )
		{
			
			_Inertia = transform.forward;
			
			bCrash = true;
			
			cEngine CurrentEngine = (cEngine)Engine.GetComponent("cEngine");//("Engine");

			//CurrentEngine.AddDamage( Speed * coll.relativeVelocity.magnitude );
			CurrentEngine.AddDamage( Speed * 0.1f );
			Speed *= 0.7f;

			RaycastHit hit;
			//Vector3 carAng = obj.transform.position - transform.position;
			//carAng.Normalize();
	        //if (Physics.Raycast(transform.position, obj.transform.position , out hit ) )
			Vector3 carAng = obj.transform.position - transform.position;
			float fDist = carAng.sqrMagnitude;
			carAng.Normalize();
			//_Crash2Normal = -carAng;
			Debug.Log ("Check Ray:" + obj.name );
			
			_cPos = transform.position;
			_cPos.y = 2;
			_cRay = obj.transform.position;

			if (Physics.Raycast(transform.position, carAng, out hit, fDist ) )
			//if (Physics.Raycast(_cPos, obj.transform.position , out hit ) )
			{
				Debug.Log ("Find Ray:" + hit.collider.name );
				/*
				// 반사작으로 튀기게...
				Vector3 vThis = transform.forward;
				//Vector3 vD = new Vector3( ( -vThis.x * hit.normal.x ) * 2f * hit.normal.x, ( -vThis.y * hit.normal.y ) * 2 * hit.normal.y, ( -vThis.z * hit.normal.z ) * 2* hit.normal.z );
				Vector3 vD = new Vector3( ( -vThis.x * hit.normal.x ) * 2f * hit.normal.x, 0f, ( -vThis.z * hit.normal.z ) * 2* hit.normal.z );
				vD = vD + vThis;
				vD.Normalize();
				transform.rotation = Quaternion.LookRotation( vD );
				*/
				
				// 미끄러지게...
				/**/
				Vector3 vThis = transform.forward;// * Speed;
				
				Vector3 vD = new Vector3( vThis.x-( vThis.x * hit.normal.x ) * hit.normal.x, 0f, vThis.z-( vThis.z * hit.normal.z ) * hit.normal.z );
				
				vD.Normalize();
				
				//transform.rotation = Quaternion.LookRotation( vD * Time.deltaTime );
				/**/
				
				// 밀어낸다...
				/**/
				_Crash2Normal = new Vector3( hit.normal.x, hit.normal.y, hit.normal.z);
				//_Crash2Normal.y = 0;
				Debug.Log("Cr : " + hit.normal.ToString() );
				/**/
				//transform.Translate( _Crash2Normal;
				
			}
			
		}
		
	}
	
}
